package com.base.kotlin.mvp

import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.OnLifecycleEvent
import com.base.delegate.weak
import com.base.kotlin.IModel
import io.reactivex.disposables.Disposable

abstract class BasePresenter<V : IView, M : IModel<*>> : LifecycleObserver {
    protected var mView: V? by weak()
    protected var mModel: M? = null
    protected var mDisposables = LinkedHashSet<Disposable>()

    protected abstract fun getModel(): M?

    /**
     * 绑定view，一般在初始化中调用该方法
     *
     * @param view view
     */
    fun attachView(view: V) {
        mView = view
        mModel = getModel()
    }

    /**
     * 解除绑定view，一般在onDestroy中调用
     */

    fun detachView() {
        mModel?.destroy()
        mModel = null
        mView = null
    }

    /**
     * View是否绑定
     *
     * @return
     */
    fun isViewAttached(): Boolean {
        return mView != null
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    open fun onCreate() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    open fun onStart() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    open fun onResume() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    open fun onPause() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    open fun onStop() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    open fun onDestroy() {
        for (disposable in mDisposables) {
            disposable.dispose()
        }
        detachView()
    }
}